package com.cdn.allmobilestore.adapter;

import java.util.ArrayList;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.cdn.allmobilestore.R;
import com.cdn.allmobilestore.model.AppInfo;
import com.cdn.allmobilestore.model.LocalAppInfo;
import com.cdn.allmobilestore.ulti.Log;
  

public class AppInstalledAdapter extends BaseAdapter {
	private LayoutInflater mInflater;

	   private ArrayList<LocalAppInfo> mApps;
	   private ArrayList<LocalAppInfo> mAppsOrig;
	   /** a map which maps the package name of an app to its icon drawable */
	   private Map<String, Drawable> mIcons;
	   private Drawable mStdImg;
	   private Context mContext;
	   PopupWindow popupMenu;
	   /**
	    * Constructor.
	    * 
	    * @param context the application context which is needed for the layout inflater
	    */
	   public AppInstalledAdapter(Context context) {
	      // cache the LayoutInflater to avoid asking for a new one each time
	      mInflater = LayoutInflater.from(context);
	      
	      // set the default icon until the actual icon is loaded for an app
	      mStdImg = context.getResources().getDrawable(R.drawable.place_holder_icon);
	      
	      mContext = context;
	   }
	   
	   @Override
	   public int getCount() {
	      return mApps.size();
	   }
	   
	   @Override
	   public Object getItem(int position) {
	      return mApps.get(position);
	   }
	   
	   @Override
	   public long getItemId(int position) {
	      return position;
	   }
	   
	   public Filter getFilter() {
		    return new Filter() {

		        @Override
		        protected FilterResults performFiltering(CharSequence constraint) {
		            final FilterResults oReturn = new FilterResults();
		            final ArrayList<LocalAppInfo> results = new ArrayList<LocalAppInfo>();
		            if (mAppsOrig == null)
		            	mAppsOrig = mApps;
		            if (constraint != null) {
		                if (mAppsOrig != null && mAppsOrig.size() > 0) {
		                    for (final LocalAppInfo app : mAppsOrig) {
		                        if (app.getName().toLowerCase()
		                                .contains(constraint.toString()))
		                            results.add(app);
		                    }
		                }
		                oReturn.values = results;
		            }
		            return oReturn;
		        }

		        @SuppressWarnings("unchecked")
		        @Override
		        protected void publishResults(CharSequence constraint,
		                FilterResults results) {
		            mApps = (ArrayList<LocalAppInfo>) results.values;
		            notifyDataSetChanged();
		        }
		    };
		}

		public void notifyDataSetChanged() {
		    super.notifyDataSetChanged();		   
		}
	   
	   @Override
	   public View getView(int position, View convertView, ViewGroup parent) {
		   final View cnv = convertView;
		  final LocalAppInfo app = mApps.get(position);
	      AppViewHolder holder;
	      final Context mContext =parent.getContext();
	      final String[] menuItems = mContext.getResources().getStringArray(R.array.installedapp_menu);
	      if(convertView == null) {
	         convertView = mInflater.inflate(R.layout.installedapp_list_item, null);	         
	      
	         
	         // creates a ViewHolder and stores a reference to the children view we want to bind data to
	         holder = new AppViewHolder();
	         holder.mTitle = (TextView) convertView.findViewById(R.id.installedapp_name);
	         holder.mIcon = (ImageView) convertView.findViewById(R.id.installedapp_photo);
	         holder.mSize = (TextView) convertView.findViewById(R.id.installedapp_size);
	         holder.mMenu = (ImageView)convertView.findViewById(R.id.installedapp_menu);
	        
	         convertView.setTag(holder);
	      } else { 
	         // reuse/overwrite the view passed assuming(!) that it is castable!
	         holder = (AppViewHolder) convertView.getTag();
	      }
	      convertView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent;

				    if (android.os.Build.VERSION.SDK_INT >= 9) {
				        /* on 2.3 and newer, use APPLICATION_DETAILS_SETTINGS with proper URI */
				        Uri packageURI = Uri.parse("package:" + app.getPackageName());
				        intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS", packageURI);
				        mContext.startActivity(intent);
				    }  else  {
				        /* on older Androids, use trick to show app details */
				        intent = new Intent(Intent.ACTION_VIEW); 
				        intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails"); 
				        intent.putExtra("com.android.settings.ApplicationPkgName", app.getPackageName()); 
				        intent.putExtra("pkg", app.getPackageName()); 
				        mContext.startActivity(intent);          
				    }
				    
				   
				}
			});
	
	      holder.setTitle(app.getName());
	      holder.setmSize(app.getSize());
	      if (mIcons == null || mIcons.get(app.getPackageName()) == null) {
	         holder.setIcon(mStdImg);
	      } else {
	         holder.setIcon(mIcons.get(app.getPackageName()));
	      }
	      holder.mMenu.setOnClickListener(new View.OnClickListener() {				
				@Override
				public void onClick(View v) {
					Log.v("on menu clicked");
					
					PopupWindow popupWindow = new PopupWindow(mContext);

			        // the drop down list is a list view
			        ListView listview = new ListView(mContext);
			        
			        // set our adapter and pass our pop up window contents
			        listview.setAdapter(menuAdapter(menuItems));
			        
			        // set the item click listener
			        listview.setOnItemClickListener(new OnItemClickListener() {
			        	@Override
			            public void onItemClick(AdapterView<?> adapter, View view, int position, long arg)   {			           
			        		String selectedItemText = ((TextView) view).getText().toString();
			            	Log.v(selectedItemText);
			            	if(selectedItemText.equals(mContext.getString(R.string.un_install)))
			            	{
			            		Intent intent = new Intent(Intent.ACTION_DELETE, Uri.fromParts("package",
			            		mContext.getPackageManager().getPackageArchiveInfo(app.getSource(), 0).packageName,null));
			            		mContext.startActivity(intent);
			            	}
			            	else if(selectedItemText.equals(mContext.getString(R.string.search_on_appstore)))
			            	{
			            		Intent intent = new Intent(Intent.ACTION_VIEW);
			            		intent.setData(Uri.parse("market://details?id="+ app.getPackageName()));
			            		mContext.startActivity(intent);
			            	}			            
			            }
			        });

			        // some other visual settings
			        popupWindow.setFocusable(true);
			        popupWindow.setWidth(250);
			        popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
			        
			        // set the list view as pop up window content
			        popupWindow.setContentView(listview);
			        popupWindow.showAsDropDown(v, 0, -5);
			       
			        
				}
			});
	      return convertView; 
	   }
	   
	   /**
	    * Sets the list of apps to be displayed.
	    * 
	    * @param list the list of apps to be displayed
	    */
	   public void setListItems(ArrayList<LocalAppInfo> list) { 
	      mApps = list; 
	   }
	   
	   /**
	    * Sets the map containing the icons for each displayed app.
	    * 
	    * @param icons the map which maps the app's package name to its icon
	    */
	   public void setIcons(Map<String, Drawable> icons) {
	      this.mIcons = icons;
	   }
	   
	   /**
	    * Returns the map containing the icons for each displayed app.
	    * 
	    * @return a map which contains a mapping of package names to icon drawable for all displayed apps
	    */
	   public Map<String, Drawable> getIcons() {
	      return mIcons;
	   }
	   
	   /**
	    * A view holder which is used to re/use views inside a list.
	    */
	   public class AppViewHolder {
	   

		private TextView mTitle;
	      private ImageView mIcon;
	      private TextView mSize;
	      private ImageView mMenu;
	      /**
	       * Sets the text to be shown as the app's title
	       * 
	       * @param title the text to be shown inside the list row
	       */
	      public void setTitle(String title) {
	         mTitle.setText(title);
	      }
	      
	      
	      /**
		 * @return the mSize
		 */
			public TextView getmSize() {
				return mSize;
			}
	
			/**
			 * @param mSize the mSize to set
			 */
			public void setmSize(float mSize) {
				Log.v("size:"  + mSize);
				this.mSize.setText(String.format("%.2f", mSize) + " MB");
			}
	      
	      /**
	       * Sets the icon to be shown next to the app's title
	       * 
	       * @param img the icon drawable to be displayed
	       */
	      public void setIcon(Drawable img) {
	         if (img != null) {
	            mIcon.setImageDrawable(img);
	         }
	      }
	   }

	   
	   
	   /*
	     * adapter where the list values will be set
	     */
	    private ArrayAdapter<String> menuAdapter(String items[]) {

	        ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, items) {

	            @Override
	            public View getView(int position, View convertView, ViewGroup parent) {

	                // setting the ID and text for every items in the list
	                String text = getItem(position);
	                
	                // visual settings for the list item
	                TextView listItem = new TextView(mContext);
	                listItem.setText(text);
	                listItem.setTag(text);
	                listItem.setTextSize(12);
	                listItem.setPadding(5,5,5,5);
	                listItem.setTextColor(Color.WHITE);
	                
	                return listItem;
	            }
	        };
	        
	        return adapter;
	    }
	   
	}
